<template>
    <div  class="container w-50 m-auto border border-1 shadow p-5">
      <table class="table table-hover">
        <thead>
        <tr style="color: white;background-color: black;">
            <th>序号</th>
            <th>商品名称</th>
            <th>数量（台）</th>
            <th>商品单价（元/台）</th>
            <th>操作</th>
        </tr>
      </thead>
        <tbody>
          <template v-if="list.length > 0">
            <tr v-for="(item, index) in list ">
            <td>{{ item.pid }}</td>
            <td>{{item.pname}}</td>
            <td>
              <button type="button" class="btn btn-outline-primary" @click="handlerCount($event, -1, item.pid)">-</button>
              {{item.count}}
              <button type="button" class="btn btn-outline-success" @click="handlerCount($event, 1, item.pid)">+</button>
            </td>
            <td>{{item.price}}</td>
            <td>
              <button type="button" class="btn btn-outline-danger" @click="del($event, item.pid)">删除</button>
            </td>
          </tr>
          </template>
          <template v-else>
            <tr>
              <td>暂无数据</td>
            </tr>
          </template>
         
        </tbody>
      </table>
      <hr>
      <h2 v-show="list.length > 0">总计: {{ priceTotal }} 元</h2>
    </div>
  </template>
  
  <script setup>
  import { ref,computed } from 'vue';
  const list = ref([
  {
        pid: '1',
        pname: 'IPhoneX',
        count: 2,
        price: 7999
      },
      {
        pid: '2',
        pname: '荣耀16',
        count: 5,
        price: 2399
      },
      {
        pid: '3',
        pname: '华为P22',
        count: 3,
        price: 3399
      },
      {
        pid: '4',
        pname: '小米9',
        count: 4,
        price: 3999
      }

  ]);
  
// 删除事件
const del = (e, _pid) => {
  list.value = list.value.filter(item => item.pid != _pid);
}

// 操作对应票据的数量
const handlerCount = (e, _count, _pid) => {
  list.value.forEach(item => {
    if(item.pid == _pid) {
      if(_count < 0 && item.count > 0) --item.count;
      else if( _count > 0 ) ++item.count;
    }
  });
}

// 总和
const priceTotal = computed({
  set(newValue){
    list.value = newValue;
  },
  get(){
    return list.value.reduce((acc,item)=>{
      return acc+item.count*item.price;
    },0)
  }
})

</script>

<style lang="scss" scoped>
</style>